<template>
  <div class="chart-container ps_w_h_100" ref="chartContainer">
    <div ref="chartDOM" class="ps_w_h_100"></div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import world from "@/utils/world.json";
echarts.registerMap("world", world);
const props = defineProps({
  option: {
    type: Object,
    required: true,
  },
  autoSet: {
    type: Boolean,
    default: true,
  },
});

const chartDOM = ref();
let myChart;
const observerDom = ref();
const chartContainer = ref();

const chartInitOption = ref({
  renderer: "svg",
});

const defaultOption = ref({
  backgroundColor: "",
  darkMode: "auto",
});

const loadChart = async () => {
  nextTick(() => {
    // const isHaveChart = echarts.getInstanceByDom(chartDOM.value)

    if (myChart != null && myChart != "" && myChart != undefined) {
      myChart.dispose();
      window.removeEventListener("resize", () => {
        myChart.resize();
      });
      myChart = null;
      observerDom.value?.disconnect();
    }
    myChart && myChart.dispose();
    observerDom.value && observerDom.value.disconnect();

    myChart = echarts.init(chartDOM.value, null, chartInitOption.value);
    const replacer = (key, value) => {
      if (typeof value === "function") {
        return value.toString();
      }
      return value;
    };

    const option = Object.assign(props.option, defaultOption.value);
    // 合并传入的配置以及默认配置
    myChart.setOption(option);
    window.addEventListener("resize", () => {
      myChart.resize();
    });
    observerDom.value = new ResizeObserver(() => {
      myChart.resize();
    });

    if (chartContainer.value) {
      observerDom.value.observe(chartContainer.value, { box: "border-box" });
    }
  });
};
const countValue = ref(0);

const updateChartOption = (option) => {
  myChart.setOption(option);
};
defineExpose({
  updateChartOption,
});
watch(
  () => props.option,
  () => {
    if (props.autoSet || countValue.value === 0) {
      loadChart();
      countValue.value += 1;
    }
  },
  { deep: true, immediate: true }
);

onMounted(loadChart);
onUnmounted(() => {
  window.removeEventListener("resize", () => {
    myChart.resize();
  });
  myChart && myChart.dispose();
  observerDom.value?.disconnect();
});
</script>

<style scoped lang="scss">
.chart-container {
  position: relative;
}
</style>
